package chain

import "fmt"

type BaseHandler interface {
	execute()
	add(next BaseHandler)
}

type handler struct {
	next    BaseHandler
	execute func()
}

func (h *handler) add(next BaseHandler) {
	h.next = next
}

type Builder struct {
	head BaseHandler
	tail BaseHandler
}

func NewBuilder() *Builder {
	return &Builder{
		tail: nil, head: nil,
	}
}

func (b *Builder) Add(next BaseHandler) *Builder {
	if b.head == nil {
		b.tail, b.head = next, next
		return b
	}
	b.tail.add(next)
	b.tail = next
	return b
}

func (b Builder) Build() BaseHandler {
	return b.head
}

type OneHandler struct {
	handler
}

func NewOneHandler() BaseHandler {
	o := new(OneHandler)
	o.handler = handler{
		execute: o.execute,
	}
	return o
}

func (o *OneHandler) execute() {
	fmt.Println("第一个Handler执行")
	if next := o.next; next != nil {
		next.execute()
	}
}

type TwoHandler struct {
	handler
}

func NewTwoHandler() BaseHandler {
	o := new(OneHandler)
	o.handler = handler{
		execute: o.execute,
	}
	return o
}

func (o *TwoHandler) execute() {
	fmt.Println("第二个Handler执行")
	if next := o.next; next != nil {
		next.execute()
	}
}

type ThreeHandler struct {
	handler
}

func NewThreeHandler() BaseHandler {
	o := new(OneHandler)
	o.handler = handler{
		execute: o.execute,
	}
	return o
}

func (o *ThreeHandler) execute() {
	fmt.Println("第三个Handler执行")
	if next := o.next; next != nil {
		next.execute()
	}
}
